#!/bin/bash - 
#===============================================================================
#
#          FILE:  ex9-11.sh
# 
#         USAGE:  ./ex9-11.sh 
# 
#   DESCRIPTION:  $RANDOM returns a different random integer at each invocation.
# 
#       OPTIONS:  ---
#  REQUIREMENTS:  ---
#          BUGS:  ---
#         NOTES:  ---
#        AUTHOR: bucunzai (), freecityer@gmail.com
#       COMPANY: FreeCity
#       CREATED: 2011年02月04日 20时53分01秒 CST
#      REVISION:  ---
#===============================================================================

set -o nounset                              # Treat unset variables as an error

MAXCOUNT=10
count=1
echo
echo "$MAXCOUNT random number:"
echo "--------------"

while [ "$count" -le $MAXCOUNT ] ; do
    number=$RANDOM
    echo $number
    let "count+=1" #Incremen count.
done
echo "-------------"

# a random int within a certain range, use modulo operator
RANGE=1000

echo
number=$RANDOM
let "number %= $RANGE"
echo "Random number less than $RANGE --- $number"

echo

# a random int  greater than a lower bound,
FLOOR=200
number=0 #initialize
while [ "$number" -le $FLOOR ] ; do
    number=$RANDOM
done
echo "Random number greater than $FLOOR --- $number"
echo

# Combine above two techniques to retrieve random number between two limits.
number=0 #initialize
while [ "$number" -le $FLOOR ] ; do
    number=$RANDOM
    let "number %= $RANGE" # Scales $number down within $RANGE.
done
echo "Random number between $FLOOR and $RANGE --- $number"
echo

# Generate binary choice, that is, "true" or "false" value.
BINARY=2
T=1
number=$RANDOM
let "number %= $BINARY"
# Note that let "number >>= 14" gives a better random distribution
#+ (right shifts out everything except last binary digit).

if [ "$number" -eq $T ]; then
    echo "TRUE"
else
    echo "FALSE"
fi
echo

# Generate a toss of the dice
SPOTS=6 # Modulo 6 gives range 0-5
        # Incremeting by 1 gives desired range of 1-6
die1=0
die2=0
# Tosses each die separately, and so gives correct odds.
let "die1 = $RANDOM % $SPOTS +1"
let "die2 = $RANDOM % $SPOTS +1" #Roll second one.
#Which arithmetic operation, above, has greater precedence --
#+ modulo (%) or additon(+)?
let "throw = $die1 + $die2"
echo "Throw of the dice = $throw"
echo
exit 0
